package efr.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.Session;

import efr.dao.PoezieDao;
import efr.entity.Poezie;
import efr.util.HibernateUtil;

public class PoezieDaoImpl implements PoezieDao {
	
	private static Logger logger = Logger.getLogger(PoezieDaoImpl.class);

	@SuppressWarnings("unchecked")
	@Override
	public List<Poezie> getAllPoezii() {
		List<Poezie> listPoezii = null;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		listPoezii = session.createQuery("FROM Poezie").list();
		for (Poezie poezie : listPoezii) {
			Hibernate.initialize(poezie.getAutor());
		}
		session.getTransaction().commit();
		return listPoezii;
	}

	@Override
	public Poezie getPoezie(int id) {
		Poezie poezie = null;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		poezie = (Poezie)session.get(Poezie.class, id);
		Hibernate.initialize(poezie.getAutor());
		session.getTransaction().commit();
		return poezie;
	}

	@Override
	public void updatedPoezie(Poezie poezie) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.update(poezie);
		Hibernate.initialize(poezie.getAutor());
		session.getTransaction().commit();
		
	}

	@Override
	public Integer addPoezie(Poezie poezie) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Poezie> listPoezii = session.createQuery("FROM Poezie P WHERE P.poezieDefault = 1 ").list();
//		Poezie p = getPoezieDefault();
		Poezie p = listPoezii.get(0);
		p.setPoezieDefault(0);
		session.update(p);
		Integer id = (Integer)session.save(poezie);
		logger.debug("UNDEFAULT: "+p);
		logger.debug("DEFAULT: "+poezie);
		session.getTransaction().commit();
		return id;
	}

	@Override
	public void deletePoezie(Poezie poezie) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.delete(poezie);
		session.getTransaction().commit();
	}

	@Override
	public Poezie getPoezieDefault() {
		List<Poezie> listPoezii = null;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		listPoezii = session.createQuery("FROM Poezie P WHERE P.poezieDefault = 1 ").list();
//		for (Poezie poezie : listPoezii) {
//			Hibernate.initialize(poezie.getAutor());
//		}
		session.getTransaction().commit();
		return listPoezii.get(0);
	}
}
